package com.web.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.web.dao.SysUserDao;
import com.web.entity.SysUser;
import com.web.service.SysUserService;

@Service
public class SysUserServiceImpl implements SysUserService {

	@Autowired
	private SysUserDao sysUserDao;

	@Autowired
	private HttpSession session;

	@Override
	public void addUser(SysUser sysUser) {

		sysUserDao.addSysUser(sysUser);
	}

	@Override
	public Map<String, Object> doLogin(String userNum, String password) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<SysUser> userslist = sysUserDao.selectUserdoLogin(userNum, password);
		String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
		// System.out.println("@@@@@@@@@@@@@@@" + md5Password);
		// System.out.println("@@@@@@@@@@@@@@@" + userslist.get(0).getPassword());
		System.out.println(md5Password.equals(userslist.get(0).getPassword()));
		if (userslist.size() == 1) {
			if (md5Password.equals(userslist.get(0).getPassword())) {
				resultMap.put("result", 1);
				this.session.setAttribute("SysUser", userslist);
			} else {
				resultMap.put("result", 3);
			}
		}
		if (userslist.size() == 0) {
			resultMap.put("result", 0);
		}
		if (userslist.size() > 1) {
			resultMap.put("result", 2);
		}

		return resultMap;
	}

	@Override
	public PageInfo getListByPage(SysUser su, Integer pageNum, Integer pageSize) {
		// TODO Auto-generated method stub
		PageHelper.startPage(pageNum, pageSize); // 调用分页功能
		List<SysUser> list = sysUserDao.getList(su); // 上面的分页会自动注入到本条查询中
		System.out.println(JSONObject.toJSON(list));
		PageInfo<SysUser> pageInfo = new PageInfo<SysUser>(list); // 获取分页信息
		System.out.println(JSONObject.toJSON(pageInfo));
		return pageInfo;
	}

	@Override
	public Map<String, Object> ResetUserPassword(SysUser sysUser) {
		Map<String, Object> map = new HashMap<String, Object>();
		sysUserDao.ResetUserPassword(sysUser);
		map.put("result", 1);
		return map;
	}

}
